package ins.wink.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import ins.wink.entity.Userinfo;
import ins.wink.service.UserInfoService;
import ins.wink.utils.MD5Utils;
/**
 * 用户controller层
 */
@Controller
public class UserInfoController {
	//注入service层
	@Autowired
	private UserInfoService userInfoService;
	
	//登录
	@RequestMapping(value="/login",method=RequestMethod.POST)
	@ResponseBody
	public Userinfo login(Userinfo user,HttpServletRequest request) {
		Userinfo u = userInfoService.logins(user);
		if(u!=null) {
			//密码在进行加密进行对比
			String password = MD5Utils.md5(user.getPassword());
			user.setPassword(password);
			if(u.getPassword().equals(password)) {
				//登陆成功将值传入session回话中
				request.getSession().setAttribute("user", u);
				return u;
			}else{
				return null;
			}
		}else {
			return null;
		}
	}
	
	
	/**
	 * 注册
	 */
	//注册前查询用户名是否存在
	@RequestMapping(value="/yanzheng",method=RequestMethod.GET)
	@ResponseBody
	public String yanzheng(Userinfo user,HttpServletRequest request) {
		Userinfo u = userInfoService.logins(user);
		if(u == null) {
			return "ok";
		}else {
			return "no";
		}
	}
	//注册
	@RequestMapping(value="/register",method=RequestMethod.POST)
	public String register(Userinfo user) {
		//注册时通过MD5加密获取密码
		String password = MD5Utils.md5(user.getPassword());
		//重新赋值
		Userinfo user1 = new Userinfo();
		user1.setUsername(user.getUsername());
		user1.setPassword(password);
		
		int i = userInfoService.insertUsers(user1);
		if(i!=0) {
			return "login";
		}else{
			return "register";
		}
	}
	/**
	 * 主页面
	 */
	@RequestMapping(value="/goodlist")
	public String goodlist() {
		return "WEB-INF/tree/home";
	}
	//重新登陆销毁session
	@RequestMapping("/userAction_toLogin")
	public String userAction_toLogin(HttpServletRequest request) {
		//销毁session
		request.getSession().removeAttribute("user");
		return "login";
	}
}
